<template>
	<div class="zhiShiFenLei">
		<!-- 主体表格 -->
		<div class="left">
			<div class="bfff left-bottom">
				<div class="center flex-start fWrap table-head">
					<el-button class="primary" type="primary" @click="addList" v-auth="['knowledge:kbBanner:save']"
						>+新增</el-button
					>
					<el-button
						class="danger"
						type="danger"
						@click="delDirectory"
						plain
						v-auth="['knowledge:kbBanner:deleteBatch']"
						>批量删除
					</el-button>
				</div>
				<div class="table-scrol">
					<el-table :data="tableData" style="width: 100%" @select="selectClick" @select-all="selectClick">
						<el-table-column align="center" type="selection" min-width="60" />
						<el-table-column align="center" prop="pcImage" label="背景图片" min-width="250">
							<template #default="{ row }">
								<div class="pcImage">
									<img :src="row.pcImage" alt="" />
								</div>
							</template>
						</el-table-column>
						<el-table-column align="center" prop="weight" label="权重" min-width="100" />
						<el-table-column align="center" prop="status" label="状态" min-width="200">
							<template #default="{ row }">
								<el-switch
									v-model="row.status"
									:active-value="qiyong"
									:inactive-value="jinyong"
									@change="controlStatus(row)"
									active-text="启用"
								/>
							</template>
						</el-table-column>
						<el-table-column align="center" prop="address" label="操作" min-width="200">
							<template #default="{ row }">
								<div class="table-color">
									<el-button
										plain
										:icon="EditPen"
										@click="modify(row)"
										v-auth="['knowledge:kbBanner:edit', 'knowledge:kbBanner:info']"
									></el-button>
									<el-button
										plain
										:icon="Delete"
										@click="delTable(row)"
										v-auth="['knowledge:kbBanner:delete']"
									></el-button>
								</div>
							</template>
						</el-table-column>
						<template #empty>
							<el-empty description="暂无数据" />
						</template>
					</el-table>
					<div class="bfff pagination-class">
						<v-pagination
							:total="total"
							v-model:size="pageSize"
							v-model:page="current"
							@pagination="fetchList"
							@paginations="fetchLists"
						></v-pagination>
					</div>
				</div>
			</div>
		</div>
		<el-dialog
			class="cheng-dialog"
			v-model="visible"
			:show-close="false"
			:before-close="quxiao"
			:close-on-click-modal="false"
			destroy-on-close
			width="800px"
		>
			<template #header="{ close, titleId, titleClass }">
				<div class="dialog-header center btheme cfff">
					<img src="@/assets/image/houTai/xqun.png" alt="" />
					<div class="flex f16 fbold">{{ title }}</div>
					<el-icon class="pointer" size="20" color="#fff" @click="quxiao">
						<Close />
					</el-icon>
				</div>
			</template>
			<div class="dialog-content">
				<el-form
					ref="ruleFormRef"
					:model="ruleForm"
					:rules="rules"
					class="demo-ruleForm"
					status-icon
					@submit.native.prevent
				>
					<div class="center">
						<div class="flex">
							<el-form-item label="背景图" prop="pcImage">
								<el-upload
									class="avatar-uploader"
									action="/"
									:before-upload="beforeAvatarUpload"
									:auto-upload="false"
									:on-change="onChangeUpload"
									ref="upload"
									:show-file-list="false"
								>
									<img v-if="ruleForm.pcImage" :src="ruleForm.pcImage" class="avatar" />
									<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
									<template #tip>
										<div class="el-upload__tip">
											推荐尺寸<span style="color: red">1920 * 260</span>
										</div>
										<div class="el-upload__tip">
											请上传 大小不超过<span style="color: red">5MB</span>格式为<span
												style="color: red"
												>jpg/png</span
											>的文件
										</div>
									</template>
								</el-upload>
								<VCropper
									ref="cropper"
									@success="handleAvatarSuccess"
									:size="5"
									:autoCropWidth="384"
									:autoCropHeight="52"
									:fixed="false"
									mode="1920px 260px"
									:centerBox="false"
									:enlarge="5"
								></VCropper>
							</el-form-item>
							<el-form-item label="权重" prop="weight">
								<template #label>
									权重
									<el-tooltip
										class="box-item"
										effect="dark"
										content="数字越大越靠前"
										placement="top"
										:offset="0"
									>
										<el-icon class="label-icon"><InfoFilled /></el-icon>
									</el-tooltip>
								</template>
								<template #default>
									<el-input-number v-model="ruleForm.weight" :min="1" @change="handleChange" />
								</template>
							</el-form-item>
							<el-form-item label="状态" prop="status">
								<el-switch
									v-model="ruleForm.status"
									:active-value="qiyong"
									:inactive-value="jinyong"
									active-text="启用"
								/>
							</el-form-item>
						</div>
					</div>
				</el-form>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="quxiao">取消</el-button>
					<el-button type="primary" @click="submitForm(ruleFormRef)"> 确定 </el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
import { Delete, EditPen } from "@element-plus/icons-vue"
import { ElMessage, ElMessageBox } from "element-plus"
import VCropper from "../../../components/cropper/index.vue"
const route = useRoute()
const router = useRouter()
const total = ref(0)
const tableData = ref([])
const qiyong = ref(1)
const jinyong = ref(2)
const title = ref("新增")
const switchValue = ref(false)
const visible = ref(false)
const fabu = ref(false)
const modifyId = ref("")
const tableList = ref([])
const ruleFormRef = ref()
const current = ref(1)
const pageSize = ref(10)
const ruleForm = reactive({
	pcImage: "",
	status: 1,
	weight: 1,
})

const rules = reactive({
	pcImage: [
		{
			required: true,
			message: "请上传背景图",
			trigger: "blur",
		},
	],
})

async function list() {
	const res = await getAxios(`/knowledge/kbBanner/page?current=${current.value}&size=${pageSize.value}`)
	total.value = +res.total
	tableData.value = res.records
	tableList.value = []
}
list()
//新增
const addList = () => {
	title.value = "新增"
	visible.value = true
}

//上传
const beforeAvatarUpload = rawFile => {
	if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
		ElMessage.error("请上传png/jpeg格式文件")
		return false
	} else if (rawFile.size / 1024 / 1024 > 5) {
		ElMessage.error("图片大小不能超过5MB!")
		return false
	}
	return true
}

const upfile = async params => {
	const file = params.file
	const formData = new FormData()
	formData.append("upfile", file)
	const { url } = await postAxios("/system/oss/upload", formData)
	ruleForm.pcImage = url
}

// 提交
const submitForm = async formEl => {
	if (fabu.value) {
		return
	} else {
		fabu.value = true
		if (!formEl) return
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				let obj = {}
				obj.pcImage = ruleForm.pcImage
				obj.weight = ruleForm.weight
				obj.status = ruleForm.status
				try {
					if (title.value == "新增") {
						await postAxios("/knowledge/kbBanner/save", obj)
						ElMessage.success("保存成功")
					} else {
						obj.id = modifyId.value
						await postAxios("/knowledge/kbBanner/edit", obj)
						ElMessage.success("编辑成功")
					}
					fabu.value = false
					visible.value = false
					list()
					del()
				} catch (error) {
					ElMessage.error(error)
					fabu.value = false
				}
			} else {
				ElMessage.error("请填入必填项")
				fabu.value = false
			}
		})
	}
}
// 清空
function del() {
	ruleForm.pcImage = ""
	ruleForm.weight = 1
	ruleForm.status = 1
}
//关闭弹窗
const quxiao = () => {
	visible.value = false
	del()
}

//修改
const modify = val => {
	title.value = "编辑"
	modifyId.value = val.id
	ruleForm.pcImage = val.pcImage
	ruleForm.weight = val.weight
	ruleForm.status = val.status
	visible.value = true
}

//分页
const fetchList = () => {
	list()
}
const fetchLists = () => {
	list()
}

const delTable = val => {
	ElMessageBox.confirm("是否确认删除", "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(async () => {
		try {
			await postAxios(`/knowledge/kbBanner/delete?id=${val.id}`)
			ElMessage.success("删除成功")
			list()
		} catch (error) {
			ElMessage.error(error)
		}
	})
}

//表格选择
const selectClick = val => {
	tableList.value = val
}

//批量删除
const delDirectory = () => {
	if (tableList.value.length == 0) {
		return ElMessage.error("请选择背景图片")
	}
	ElMessageBox.confirm("是否确认删除", "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(async () => {
		let obj = []
		tableList.value.forEach(item => {
			obj.push(item.id)
		})
		try {
			await postAxios(`/knowledge/kbBanner/deleteBatch`, obj)
			list()
			ElMessage.success("删除成功")
		} catch (error) {
			ElMessage.error(error)
		}
	})
}
//启用开关
const controlStatus = async row => {
	try {
		await postAxios("/knowledge/kbBanner/edit", row)
	} catch (error) {
		if (row.status == 1) {
			row.status = 2
		} else {
			row.status = 1
		}
		ElMessage.error(error)
	}
}
onUnmounted(async () => {
	const banner = await getAxios(`/knowledge/kbBanner/list?status=1`)
	let bannerZ = []
	banner.forEach(item => {
		bannerZ.push(item.pcImage)
	})
	localStorage.setItem("bgc", bannerZ)
})

const upload = ref("")
const cropper = ref("")
// 图片裁剪
function onChangeUpload(file) {
	cropper.value.handleChangeUpload(file)
	upload.value.clearFiles()
}

//上传成功
const handleAvatarSuccess = res => {
	ruleForm.pcImage = res.url
}
</script>

<style lang="scss" scoped>
.zhiShiFenLei {
	background-color: #f8f8f8;
	// height: 100%;
	.left {
		margin: 25px;
		background-color: #fff;
		height: 100%;
		.left-bottom {
			padding: 15px;
			.table-head {
				margin-bottom: 15px;

				:deep(.el-input) {
					width: 215px;
					height: 25px;
					border-radius: 3px;
					margin-right: 5px;
				}

				.primary {
					width: 90px;
					height: 30px;
					border-radius: 3px;
				}

				.danger {
					width: 90px;
					height: 30px;
					border-radius: 3px;
					margin-left: 10px;
				}
			}
		}
	}
}
.table-color {
	:deep(.el-button) {
		&:focus {
			color: #606266;
			background-color: #fff;
			border: 1px solid #dcdfe6;
		}
	}
}
.pcImage {
	display: flex;
	justify-content: center;
	img {
		width: 100px;
		height: 60px;
	}
}
.avatar-uploader .avatar {
	width: 500px;
	// height: 178px;
	display: block;
	aspect-ratio: 1920 / 260;
	border-radius: 3px;
}
.avatar-uploader .el-upload {
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	// transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
	border: 1px dashed #ddd;
}
.box-item {
	display: flex;
	.left {
		width: 35%;
		padding: 0 25px;
		margin: 0;
	}
	.right {
		width: 60%;
		padding: 20px;
	}
}
.label-icon {
	margin-left: 10px;
	padding-top: 15px;
}
:deep(.el-dialog__body) {
	padding: 30px 80px;
}
.pagination-class {
	display: flex;
	justify-content: center;
	margin-top: 20px;
}
:deep(.cheng-dialog) {
	// width: 700px !important;
}
</style>
